package cn.goour.web.sys.entity

import cn.goour.web.sys.entity.type.ActionType
import com.fasterxml.jackson.annotation.JsonIgnore
import getRealIp
import getUserAgent
import java.io.Serializable
import java.util.*
import javax.persistence.*
import javax.servlet.http.HttpServletRequest

@Entity
data class Log(
        @field:[Id GeneratedValue(strategy = GenerationType.IDENTITY)]
        var id: Int = 0,
        var type: String = "",

        @field:[Column(insertable = false, updatable = false)]
        var user_id: Int? = 0,
        @field:[JsonIgnore ManyToOne(cascade = arrayOf(CascadeType.DETACH), fetch = FetchType.LAZY)]
        var user: User? = null,

        @field:[Column(insertable = false, updatable = false)]
        var admin_id: Int? = 0,
        @field:[JsonIgnore ManyToOne(cascade = arrayOf(CascadeType.DETACH), fetch = FetchType.LAZY)]
        var admin: Admin? = null,

        var actionType: ActionType = ActionType.None,
        var actionText: String = ActionType.None.text,

        var addIp: String = "",
        @field:[Column(columnDefinition = "Text")]
        var addUa: String = "",
        var addTime: Date = Date()
) : Serializable {
    constructor(user: User?, actionType: ActionType, actionText: String, request: HttpServletRequest) : this(user = user, actionType = actionType, actionText = actionText) {
        this.initAdd(request)
        this.type = "user"
    }

    constructor(user: User?, actionText: String, request: HttpServletRequest) : this(user = user, actionText = actionText) {
        this.initAdd(request)
        this.type = "user"
    }

    constructor(admin: Admin?, actionType: ActionType, actionText: String, request: HttpServletRequest) : this(admin = admin, actionType = actionType, actionText = actionText) {
        this.initAdd(request)
        this.type = "admin"
    }

    constructor(admin: Admin?, actionText: String, request: HttpServletRequest) : this(admin = admin, actionText = actionText) {
        this.initAdd(request)
        this.type = "admin"
    }

    fun isUser() = type == "user"

    fun isAdmin() = type == "admin"

    fun initAdd(request: HttpServletRequest) {
        this.addIp = request.getRealIp()
        this.addUa = request.getUserAgent()
    }
}